package org.jspar;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jspar.model.Module;
import org.jspar.tile.Tile;

public class Partition implements Iterable<Module> {

    private List<Module> modules = new ArrayList<Module>();
    //private ModuleString string = null;
    private Tile rootTile;
    private int xSize = 0;
    private int ySize = 0;
    //private int xPosition = 0;
    //private int yPosition = 0;
    
    public Partition() {
    }

    public Partition(List<Module> modules) {
        for (Module m : modules) {
        	add(m);
        }
    }

    public int size() {
        return modules.size();
    }

    public Module moduleAt(int i) {
        return modules.get(i);
    }
    
    public void add(Module module) {
    	modules.add(module);
    	module.setPartition(this);
	}
    
    public void remove(Module module) {
    	modules.remove(module);
	}
    
	public Iterator<Module> iterator() {
		return modules.iterator();
	}

    public void clearFlags(int flags) {
        for (Module m : modules) {
            if (!m.hasFlag(Module.PLACED))
                m.clearFlag(flags);
        }
    }
    
    
	public void setRootTile(Tile tile) {
		this.rootTile = tile;
	}

	public void fixupPartition(int xflr, int yflr) {
		xSize -= xflr;
		ySize -= yflr;

		for (Module m : modules) {
			if (m.hasFlag(Module.PLACED)) {
				m.setPosition(m.x() - xflr, m.y() - yflr);
			}
		}
		List<Tile> tl = rootTile.allspace();
		Tile.translateOrigin(tl, -1 * xflr, -1 * yflr);
	}

	public List<Module> modules() {
		return modules;
	}

	public Tile rootTile() {
		return rootTile;
	}

	public int getWidth() {
		return ySize;
	}

	public int getHeight() {
		return xSize;
	}
	
	public void setSize(int width, int height) {
		this.xSize = width;
		this.ySize = height;
	}

    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append('{');
        for (int i = 0; i < modules.size(); ++i) {
            if (i != 0)
                buffer.append(' ');
            buffer.append(modules.get(i).name());
        }
        buffer.append('}');
        return buffer.toString();
    }

}
